package com.ubigate.CooknaviHA;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.UUID;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import static com.ubigate.CooknaviHA.AssetReader.getStringFromAsset;
import com.example.android.imagedownloader.*;

public class CooknaviApp extends Application {
	public static final Integer NOTIFICATION_ID = 312596767;
	
	private static final Integer PARSE_START = 0;
	private static final Integer RECIPE_START = 10;
	private static final Integer RECIPE_TITLE = 20;
	private static final Integer RECIPE_KIND = 21;
	private static final Integer RECIPE_GROUP = 29;
	private static final Integer RECIPE_CALORY = 30;
	private static final Integer RECIPE_DURATION = 31;
	private static final Integer RECIPE_DIFFICULTY = 32;
	private static final Integer RECIPE_NATION = 33;
	private static final Integer RECIPE_THEME = 34;
	private static final Integer RECIPE_PORTION = 40;
	private static final Integer RECIPE_IMAGE = 50;
	private static final Integer RECIPE_DESCRIPTION = 51;
	private static final Integer RECIPE_PICK_INGREDIENT = 52;
	private static final Integer RECIPE_SECRET_METHOD = 53;
	private static final Integer RECIPE_PREPARATION = 54;
	private static final Integer RECIPE_INGREDIENT = 55;
	private static final Integer RECIPE_STEP = 58;
	private static final Integer RECIPE_TEXT = 70;

	private static final String TAG = "CooknaviApp";

	private int displayWidth = 0;
	private int displayHeight = 0;

	public JSONMainItems jMainItems = new JSONMainItems();
	
	private String sContentPath = "";
	
	private ArrayList<Recipe> arRecipeList = new ArrayList<Recipe>();
	public RecipeDetail oRecipeDetail = new RecipeDetail();
	
	private int state = 0;
	private String xmlRecipes = ""; 
	private int sensorType = 0;

    public File extDir = null;
    
    private static String uniqueID = null;
    private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
    private static final String PREF_CONTENT_PATH = "PREF_CONTENT_PATH";
    
	public CooknaviApp() {
	}
	@Override
	public void onCreate() {
		Log.d(TAG, "onCreate");
		super.onCreate();
		extDir = getExternalFilesDir(null);
//		Log.d(TAG, "External Dir : "+extDir.getAbsolutePath());
	}
	@Override
	public void onTerminate() {
		Log.d(TAG,"onTerminate");
		super.onTerminate();
		clearApplicationCache(null);
	}
	public synchronized static String id(Context context) {
		if (uniqueID == null) {
			SharedPreferences sp = context.getSharedPreferences(PREF_UNIQUE_ID, Context.MODE_PRIVATE);
			uniqueID = sp.getString(PREF_UNIQUE_ID, null);
			if (uniqueID == null) {
				uniqueID = UUID.randomUUID().toString();
				Editor editor = sp.edit();
				editor.putString(PREF_UNIQUE_ID, uniqueID);
				editor.commit();
			}
		}
		return uniqueID;
	}
    private void clearApplicationCache(java.io.File dir){
        if(dir==null)
            dir = getCacheDir();
        else;
        if(dir==null)
            return;
        else;
        java.io.File[] children = dir.listFiles();
        try{
            for(int i=0;i<children.length;i++)
                if(children[i].isDirectory())
                    clearApplicationCache(children[i]);
                else children[i].delete();
        }
        catch(Exception e){}
    }	
	/// 센서 타입 가져오기
	public int getSensorType() {
		return sensorType;
	}
	/// 센서 타입 설정
	public void setSensorType(int sensorType) {
		this.sensorType = sensorType;
	}
	/// 네트워크 연결상태 체크
	public int getNetworkState() {
		int nNetworkState = 0;

		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		ni.isAvailable();
		boolean isWifiConn = ni.isConnected();
//		ni = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//		boolean isMobileAvail = ni.isAvailable();
//		boolean isMobileConn = ni.isConnected();

		//if (isWifiAvail) nNetworkState++;
		if (isWifiConn) nNetworkState++;
		//if (isMobileAvail) nNetworkState++;
//		if (isMobileConn) nNetworkState++;
		
		return nNetworkState;
	}
	/// 화면 가로 사이즈 가져오기
	public int getDisplayWidth() {
        Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    	displayWidth = display.getWidth();
    	Log.i(TAG, "display width : "+ String.valueOf(displayWidth));
    	
    	return displayWidth;
	}
	/// 화면 세로 사이즈 가져오기
	public int getDisplayHeight() {
        Display display = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        displayHeight = display.getHeight();
    	Log.i(TAG, "display height : "+ String.valueOf(displayHeight));
    	
    	return displayHeight;
	}
	/// 프로그램 상태 getter/setter
	public int getState() {
		return state;
	}
	public void setState(int state) {
		this.state = state;
	}
	/// Recipe ArrayList getter/setter
	public ArrayList<Recipe> getRecipeList() {
		return arRecipeList;
	}
	public void setRecipeList(ArrayList<Recipe> arRecipeList) {
		this.arRecipeList = arRecipeList;
	}
	/// Content 저장 경로 getter/setter
	public String getContentPath() {
		return sContentPath;
	}
	public void setContentPath(String sContentPath) {
		this.sContentPath = sContentPath;
		// SharedPreference
		Log.d(TAG, "setContentPath-SharedPreference 저장");
		SharedPreferences sp = this.getSharedPreferences(PREF_CONTENT_PATH, Context.MODE_PRIVATE);
		String tContentPath = "";
		tContentPath = sp.getString(PREF_CONTENT_PATH, null);
		if (tContentPath == null) {
			tContentPath = sContentPath;
			Editor editor = sp.edit();
			editor.putString(PREF_CONTENT_PATH, tContentPath);
			editor.commit();
		}
	}
	public String LoadContentPath() {
		Log.d(TAG, "LoadContentPath 시작");
		if (sContentPath.equals("")) {
			SharedPreferences sp = this.getSharedPreferences(PREF_CONTENT_PATH, Context.MODE_PRIVATE);
			sContentPath = sp.getString(PREF_CONTENT_PATH, "");
			if (sContentPath.equals("")) ;
			else {
				Log.d(TAG, "LoadContentPath-SharedPreference 로드");
				String filename = sContentPath.substring(sContentPath.lastIndexOf("/")+1);
	        	LoadXMLRecipes(sContentPath+"/"+filename+".xml");
	            ParseXMLRecipes();
	    		ParseRecipe();
			}
		}
		return sContentPath;
	}
	/// XML Recipe 불러오기 (Asset)
	public void LoadXMLRecipes(Activity activity) {
		xmlRecipes = getStringFromAsset(activity, "recipe.xml");
		//Log.i(TAG, xmlRecipes);
	}
	/// XML Recipe 불러오기 (File)
	public void LoadXMLRecipes(String filename) {
		FileInputStream fis;
		try {
			fis = new FileInputStream(filename);
			byte [] data = new byte[fis.available()];
			while (fis.read(data) != -1) {;}
			fis.close();
			xmlRecipes = new String(data);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/// XML Recipe Parser
	public void ParseXMLRecipes() {
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			//factory.setNamespaceAware(true);

			String tsRecipeID = "";			// 레시피 ID
			String tsTitle = ""; 			// 레시피 타이틀
			String tsCalory = "";			// 레시피 칼로리
			String tsPortion = "";			// 레시피 분량
			String tsImage = "";			// 레시피 대표 이미지
			
			XmlPullParser xpp = factory.newPullParser();
			xpp.setInput(new StringReader(xmlRecipes));
			
			int eventType = xpp.getEventType();
			Log.i(TAG, "XML Parsing Start.");
			while (eventType != XmlPullParser.END_DOCUMENT) {
				//if (eventType == XmlPullParser.START_DOCUMENT) { Log.i(TAG, "XML Parsing Start."); }
				//else
				if (eventType == XmlPullParser.START_TAG) {
					String tsElementName = xpp.getName();
					if (tsElementName.equals("recipe")) {
						state = RECIPE_START;
						tsRecipeID = xpp.getAttributeValue(0);
						tsTitle = ""; tsCalory = ""; tsPortion = ""; tsImage = "";
					} else if (tsElementName.equals("title")) {
						state = RECIPE_TITLE;
					} else if (tsElementName.equals("calory")) {
						state = RECIPE_CALORY;
					} else if (tsElementName.equals("group")) {
						state = RECIPE_GROUP;
					} else if (tsElementName.equals("portion")) {
						state = RECIPE_PORTION;
					} else if (tsElementName.equals("represent_img")) {
						state = RECIPE_IMAGE;
					}
				}
				else if (eventType == XmlPullParser.END_TAG) {
					if (xpp.getName().equals("recipe")) {
						Recipe recipe = new Recipe(tsRecipeID, tsTitle, tsCalory, tsPortion, tsImage);
						arRecipeList.add(recipe);
					}					
				}
				else if (eventType == XmlPullParser.TEXT) {
					String tsText = xpp.getText().trim();
					//Log.i(TAG, "state = "+state+", text = "+tsText);
					if (state == RECIPE_TITLE) { tsTitle = tsText; }
					else if (state == RECIPE_CALORY) { tsCalory = tsText; }
					else if (state == RECIPE_PORTION) { tsPortion = tsText; }
					else if (state == RECIPE_IMAGE) { tsImage = tsText; }
					state = RECIPE_TEXT;
				}
				eventType = xpp.next();
			}
			Log.i(TAG, "XML Parsing End.");
		} catch (IOException e) { 
			Log.e(TAG, e.getMessage());
		} catch (XmlPullParserException e) {
			Log.e(TAG, e.getMessage());
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}
	}
	public void setXMLRecipes(String xmlRecipes) {
		this.xmlRecipes = xmlRecipes;
	}
	public String getXMLRecipes() {
		return xmlRecipes;
	}
	
	public void ParseRecipe() {
		//Log.i(TAG, "Get RecipeID : "+ sRecipeID);
		oRecipeDetail.ClearRecipeDetail();
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			//factory.setNamespaceAware(true);

			String tsIngredientClass = "";		// 레시피 재료 분류
			String tsIngredientID = "";			// 레시피 재료 ID (식품성분표번호)
			String tsIngredientQuantity = "";	// 레시피 재료량
			String tsIngredientUnit = "";		// 레시피 재료 단위
			
			String tsStepID = "";				// 레시피 조리단계 번호
			String tsStepDuration = "";			// 레시피 조리단계 시간
			String tsStepVGuide = "";			// 레시피 음성안내 여부 (on/off)
			String tsStepAttachment = "";		// ������ �ܰ� ���ҽ�
			String tsStepVAttachment = "";		// ������ �ܰ� ���� ���ҽ�
			String tsStepColoring = "";			// 컬러링

			XmlPullParser xpp = factory.newPullParser();
			xpp.setInput(new StringReader(xmlRecipes));
			
			int eventType = xpp.getEventType();
			Log.i(TAG, "XML Parsing Start.");
			state = PARSE_START;
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					String tsElementName = xpp.getName();
					if (tsElementName.equals("recipe")) {
						// ������ ����
						Log.i(TAG, "recipe start.");
						xpp.getAttributeValue(0);
//						if (!(sRecipeID.equals(tsRecipeID))) {
//							eventType = xpp.next();
//							continue;
//						}
						Log.i(TAG, "parsing start.");
						state = RECIPE_START;
					} else if (tsElementName.equals("title") && state != PARSE_START) {
						state = RECIPE_TITLE;	//Log.i(TAG, "RECIPE_TITLE start.");
					} else if (tsElementName.equals("kind") && state != PARSE_START) {
						state = RECIPE_KIND;	//Log.i(TAG, "RECIPE_KIND start.");
					} else if (tsElementName.equals("calory") && state != PARSE_START) {
						state = RECIPE_CALORY;	//Log.i(TAG, "RECIPE_CALORY start.");
					} else if (tsElementName.equals("group") && state != PARSE_START) {
						state = RECIPE_GROUP;	//Log.i(TAG, "RECIPE_GROUP start.");
					} else if (tsElementName.equals("duration") && state != PARSE_START) {
						state = RECIPE_DURATION;	//Log.i(TAG, "RECIPE_DURATION start.");
					} else if (tsElementName.equals("difficulty") && state != PARSE_START) {
						state = RECIPE_DIFFICULTY;	//Log.i(TAG, "RECIPE_DIFFICULTY start.");
					} else if (tsElementName.equals("nation") && state != PARSE_START) {
						state = RECIPE_NATION;	//Log.i(TAG, "RECIPE_NATION start.");
					} else if (tsElementName.equals("theme") && state != PARSE_START) {
						state = RECIPE_THEME;	//Log.i(TAG, "RECIPE_THEME start.");
					} else if (tsElementName.equals("portion") && state != PARSE_START) {
						state = RECIPE_PORTION;	//Log.i(TAG, "RECIPE_PORTION start.");
					} else if (tsElementName.equals("represent_img") && state != PARSE_START) {
						state = RECIPE_IMAGE;	//Log.i(TAG, "RECIPE_IMAGE start.");
					} else if (tsElementName.equals("description") && state != PARSE_START) {
						state = RECIPE_DESCRIPTION;	//Log.i(TAG, "RECIPE_DESCRIPTION start.");
					} else if (tsElementName.equals("pick_ingredients") && state != PARSE_START) {
						state = RECIPE_PICK_INGREDIENT;	//Log.i(TAG, "RECIPE_PICK_INGREDIENT start.");
					} else if (tsElementName.equals("secret_method") && state != PARSE_START) {
						state = RECIPE_SECRET_METHOD;	//Log.i(TAG, "RECIPE_SECRET_METHOD start.");
					} else if (tsElementName.equals("preparation") && state != PARSE_START) {
						state = RECIPE_PREPARATION;	//Log.i(TAG, "RECIPE_PREPARATION start.");
					} else if (tsElementName.equals("ingredient") && state != PARSE_START) {
						state = RECIPE_INGREDIENT;	//Log.i(TAG, "RECIPE_INGREDIENT start("+ xpp.getAttributeCount()+" attributes).");
						tsIngredientClass = xpp.getAttributeValue(4);
						tsIngredientID = xpp.getAttributeValue(0);			// ����� ID
						tsIngredientQuantity = xpp.getAttributeValue(1);	// ����� ����
						tsIngredientUnit = xpp.getAttributeValue(2);		// ����� �跮����
					} else if (tsElementName.equals("step") && state != PARSE_START) {
						state = RECIPE_STEP;	//Log.i(TAG, "RECIPE_STEP start("+ xpp.getAttributeCount()+" attributes).");
						tsStepID = xpp.getAttributeValue(0);				// �ܰ� ��
						tsStepDuration = xpp.getAttributeValue(1);			// �ܰ� ���� �ð�
						tsStepVGuide = xpp.getAttributeValue(2);			// �ܰ� ���� ���ҽ� ���翩��
						tsStepAttachment = xpp.getAttributeValue(3);		// �ܰ� ���� ���ҽ�
						tsStepVAttachment = xpp.getAttributeValue(4);		// �ܰ� ���ҽ�
						tsStepColoring = xpp.getAttributeValue(5);			// 컬러링
					}
				}
				else if (eventType == XmlPullParser.END_TAG) {
					if (xpp.getName().equals("recipe") && state != PARSE_START) {
						// ������ ��
						break;
					}					
				}
				else if (eventType == XmlPullParser.TEXT && state != PARSE_START) {
					String tsText = xpp.getText().trim();
					if (state == RECIPE_TITLE) { oRecipeDetail.setTitle(tsText); }
					else if (state == RECIPE_KIND) { oRecipeDetail.setKind(tsText); }
					else if (state == RECIPE_CALORY) { oRecipeDetail.setCalory(tsText); }
					else if (state == RECIPE_GROUP) { oRecipeDetail.setGroup(tsText); }
					else if (state == RECIPE_DURATION) { oRecipeDetail.setDuration(tsText); }
					else if (state == RECIPE_DIFFICULTY) { oRecipeDetail.setDifficulty(tsText); }
					else if (state == RECIPE_NATION) { oRecipeDetail.setNation(tsText); }
					else if (state == RECIPE_THEME) { oRecipeDetail.setTheme(tsText); }
					else if (state == RECIPE_PORTION) { oRecipeDetail.setPortion(tsText); }
					else if (state == RECIPE_IMAGE) { oRecipeDetail.setImage(tsText); }
					else if (state == RECIPE_DESCRIPTION) { oRecipeDetail.setDescription(tsText); }
					else if (state == RECIPE_PICK_INGREDIENT) { oRecipeDetail.setPickIngredients(tsText); }
					else if (state == RECIPE_SECRET_METHOD) { oRecipeDetail.setSecretMethod(tsText); }
					else if (state == RECIPE_PREPARATION) { oRecipeDetail.setPreparation(tsText); }
					else if (state == RECIPE_INGREDIENT) { 
						//Log.i(TAG, tsIngredientClass+","+tsIngredientID+","+tsText+","+tsIngredientQuantity+","+tsIngredientUnit);
						Ingredient ingredient = new Ingredient(tsIngredientClass, tsIngredientID, tsText, tsIngredientQuantity, tsIngredientUnit);
						oRecipeDetail.addIngredient(ingredient); }
					else if (state == RECIPE_STEP) {
						//Log.i(TAG, tsStepID+","+tsStepDuration+","+tsStepAttachment+","+tsText);
						Step step = new Step(tsStepID, tsStepDuration, tsStepVGuide, tsStepAttachment, tsStepVAttachment, tsStepColoring, tsText);
						oRecipeDetail.addStep(step);
					}
					state = RECIPE_TEXT;	//Log.i(TAG, "RECIPE_TEXT.");
				}
				eventType = xpp.next();	
			}
			Log.i(TAG, "XML Parsing End.");
		} catch (IOException e) { 
			Log.e(TAG, e.getMessage());
		} catch (XmlPullParserException e) {
			Log.e(TAG, e.getMessage());
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
		}		
	}
	public RecipeDetail getDetailedRecipe() {
		return oRecipeDetail;
	}
    public static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        StringBuilder sb = new StringBuilder();
        try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
			String line = null;
			reader.skip(1);
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
        } catch (UnsupportedEncodingException e) {
        	Log.d(TAG,"convertStreamToString :");
        	e.printStackTrace();
        } catch (IOException e) {
        	Log.d(TAG,"convertStreamToString :");
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            	Log.d(TAG,"convertStreamToString :");
                e.printStackTrace();
            }
		}
		return sb.toString();
    }
	public static String getHttp(String url) { 
//		Log.d(TAG, "getHttp : " + url); 
		HttpClient httpclient = new DefaultHttpClient(); 
		HttpGet httpget = new HttpGet(url); 
		HttpResponse response;

		String result = ""; 

		try { 
			response = httpclient.execute(httpget); 
			// Log.i(LOG_TAG, response.getStatusLine().toString()); 
			HttpEntity entity = response.getEntity(); 
			if (entity != null) { 
				InputStream instream = entity.getContent(); 
				result = CooknaviApp.convertStreamToString(instream);
				instream.close();
//				Log.i(TAG, result);  
				} 
		} catch (ClientProtocolException e) { 
			Log.e(TAG, "There was a protocol based error", e); 
		} catch (IOException e) { 
			Log.e(TAG, "There was an IO Stream related error", e); 
		}
		return result; 
	} 
	public static JSONObject getHttpJson(String url) { 
		JSONObject json = null; 
		String result = getHttp(url); 
		try { 
			json = new JSONObject(result.toString()); 
		} catch (JSONException e) { 
			Log.e(TAG, "There was a Json parsing based error", e); 
		} 
		return json; 
	}
}

class Recipe implements Comparable<Recipe> {
	private String Name;
	private String sRecipeID;
	private String sTitle;
	private String sCalory;
	private String sPortion;
	private String sImage;
	
	public Recipe(String sRecipeID, String sTitle, String sCalory, String sPortion, String sImage) {
		this.Name = sTitle;
		this.sRecipeID = sRecipeID; 
		this.sTitle = sTitle;
		this.sImage = sImage;
		this.sPortion = sPortion;
		this.sCalory = sCalory;
	} 
	
	public String getRecipeID() {
		return sRecipeID;
	}
	public String getTitle() {
		return sTitle;
	}
	public String getImage() {
		return sImage;
	}
	public String getPortion() {
		return sPortion;
	}
	public String getCalory() {
		return sCalory;
	}
	public int compareTo(Recipe another) {
		// TODO Auto-generated method stub
		return this.sTitle.compareToIgnoreCase(another.sTitle);
	}
	@Override
	public String toString() {
		return this.sTitle;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		Name = name;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return Name;
	}
}


class Ingredient {
	private String sIngredientID;
	private String sName;
	private String sQuantity;
	private String sUnit;
	
	public Ingredient(String sClass, String sIngredientID, String sName, String sQuantity, String sUnit) {
		this.sIngredientID = sIngredientID;
		this.sName = sName;
		this.sQuantity = sQuantity;
		this.sUnit = sUnit;
	}
	
	public String getsIngredientID() {
		return sIngredientID;
	}
	public String getIngredient() {
		return sName+sQuantity+sUnit;
	}
}


class Step {
	private String sStepID;
	private String sDuration;
	private String sVGuide;
	private String sAttachment;
	private String sVAttachment;
	private String sColoring;
	private String sDescription;
	
	public Step(String sStepID, String sDuration, String sVGuide, String sAttachement, String sVAttachment, String sColoring , String sDescription) {
		this.sStepID = sStepID;
		this.sDuration = sDuration;
		this.sVGuide = sVGuide;
		this.sAttachment = sAttachement;
		this.sVAttachment = sVAttachment;
		this.sColoring = sColoring;
		this.sDescription = sDescription;
	}
	
	public String getStepID() {
		return sStepID;
	}
	public String getDuration() {
		return sDuration;
	}
	public String getVGuide() {
		return sVGuide;
	}
	public String getVAttachment() {
		return sVAttachment;
	}
	public String getAttachment() {
		return sAttachment;
	}
	public String getDescription() {
		return sDescription;
	}
	public String getColoring() {
		return sColoring;
	}
}

class RecipeDetail {
	private static final String TAG = "CooknaviPlayer";
	
	private String sRecipeID;
	private String sTitle;
	private String sKind;
	private String sCalory;
	private String sGroup;
	private String sDuration;
	private String sDifficulty;
	private String sNation;
	private String sTheme;
	private String sPortion;
	private String sImage;
	private String sDescription;
	
	private String sPickIngredients;
	private String sSecretMethod;
	private String sPreparation;
	
	private ArrayList<Ingredient> arIngredient = new ArrayList<Ingredient> ();
	
	private ArrayList<Step> arSteps = new ArrayList<Step> ();
	
	/// RecipeDetail() Constructor
	public RecipeDetail() {
		
	}
	
	public void ClearRecipeDetail() {
		sRecipeID = "";
		sTitle = "";
		sKind = "";
		sCalory = "";
		sGroup = "";
		sDuration = "";
		sDifficulty = "";
		sNation = "";
		sTheme = "";
		sPortion = "";
		sImage = "";
		sDescription = "";
		sPickIngredients = "";
		sSecretMethod = "";
		sPreparation = "";
		
		arIngredient.clear();
		arSteps.clear();
	}
	/**
	 * @param RecipeBasicInfo (sRecipeID, sTitle, sKind, sCalory, sDuration, sDifficulty, sNation, sTheme, sPortion, sImage, sDescription) to set
	 */
	public void setRecipeBasicInfo(String sRecipeID, String sTitle, String sKind, String sCalory, String sGroup, String sDuration, String sDifficulty, String sNation, String sTheme, String sPortion, String sImage, String sDescription) {
		this.sRecipeID = sRecipeID;
		this.sTitle = sTitle;
		this.sKind = sKind;
		this.sCalory = sCalory;
		this.sGroup = sGroup;
		this.sDuration = sDuration;
		this.sDifficulty = sDifficulty;
		this.sNation = sNation;
		this.sTheme = sTheme;
		this.sPortion = sPortion;
		this.sImage = sImage;
		this.sDescription = sDescription;
	}
	/**
	 * @return sBasicInfo(sKind, sCalory, sDuration, sDifficulty, sNation, sTheme, sPortion, sDescription�� ������ ����)
	 */
	public String getRecipeBasicInfo() {
		String sBasicInfo = "";
		
		sBasicInfo = sBasicInfo +"분량:"+ sPortion +"\t조리시간:"+ sDuration +"\n";
		sBasicInfo = sBasicInfo +"칼로리:"+ sCalory +"\t난이도:"+ sDifficulty +"\n";
		sBasicInfo = sBasicInfo +"요리설명:\n"+ sDescription +"\n";
		sBasicInfo = sBasicInfo +"요리분류:"+ sKind +"\t국가별:"+ sNation +"\n";
		sBasicInfo = sBasicInfo +"주제별:"+ sTheme;
		
		return sBasicInfo;
	}
	/**
	 * @param RecipeKnowledge (sPickIngredient, sSecretMethod, sPreparation) to set
	 */
	public void setRecipeKnowledge(String sPickIngredient, String sSecretMethod, String sPreparation) {
		this.sPickIngredients = sPickIngredient;
		this.sSecretMethod = sSecretMethod;
		this.sPreparation = sPreparation;
	}
	public void addIngredient(Ingredient ingredient) {
		arIngredient.add(ingredient);
	}
	public String getRecipeIngredient() {
		String sIngredients = "";
		
		for (Ingredient ig:arIngredient) sIngredients = sIngredients + ig.getIngredient() +"\n";
		
		return sIngredients;
	}
	public void addStep(Step step) {
		arSteps.add(step);
	}
	/**
	 * @param sRecipeID the sRecipeID to set
	 */
	public void setRecipeID(String sRecipeID) {
		this.sRecipeID = sRecipeID;
	}
	/**
	 * @return the sRecipeID
	 */
	public String getRecipeID() {
		return sRecipeID;
	}
	/**
	 * @param sTitle the sTitle to set
	 */
	public void setTitle(String sTitle) {
		this.sTitle = sTitle;
	}
	/**
	 * @return the sTitle
	 */
	public String getTitle() {
		return sTitle;
	}
	/**
	 * @param sKind the sKind to set
	 */
	public void setKind(String sKind) {
		this.sKind = sKind;
	}
	/**
	 * @return the sKind
	 */
	public String getKind() {
		return sKind;
	}
	/**
	 * @param sCalory the sCalory to set
	 */
	public void setCalory(String sCalory) {
		this.sCalory = sCalory;
	}
	/**
	 * @return the sCalory
	 */
	public String getCalory() {
		return sCalory;
	}
	public String getGroup() {
		return sGroup;
	}

	public void setGroup(String sGroup) {
		this.sGroup = sGroup;
	}

	/**
	 * @param sDuration the sDuration to set
	 */
	public void setDuration(String sDuration) {
		this.sDuration = sDuration;
	}
	/**
	 * @return the sDuration
	 */
	public String getDuration() {
		return sDuration;
	}
	/**
	 * @param sDifficulty the sDifficulty to set
	 */
	public void setDifficulty(String sDifficulty) {
		this.sDifficulty = sDifficulty;
	}
	/**
	 * @return the sDifficulty
	 */
	public String getDifficulty() {
		return sDifficulty;
	}
	/**
	 * @param sNation the sNation to set
	 */
	public void setNation(String sNation) {
		this.sNation = sNation;
	}
	/**
	 * @return the sNation
	 */
	public String getNation() {
		return sNation;
	}
	/**
	 * @param sTheme the sTheme to set
	 */
	public void setTheme(String sTheme) {
		this.sTheme = sTheme;
	}
	/**
	 * @return the sTheme
	 */
	public String getTheme() {
		return sTheme;
	}
	/**
	 * @param sPortion the sPortion to set
	 */
	public void setPortion(String sPortion) {
		this.sPortion = sPortion;
	}
	/**
	 * @return the sPortion
	 */
	public String getPortion() {
		return sPortion;
	}
	/**
	 * @param sImage the sImage to set
	 */
	public void setImage(String sImage) {
		this.sImage = sImage;
	}
	/**
	 * @return the sImage
	 */
	public String getImage() {
		return sImage;
	}
	/**
	 * @param sDescription the sDescription to set
	 */
	public void setDescription(String sDescription) {
		this.sDescription = sDescription;
	}
	/**
	 * @return the sDescription
	 */
	public String getDescription() {
		return sDescription;
	}
	/**
	 * @param sPickIngredients the sPickIngredients to set
	 */
	public void setPickIngredients(String sPickIngredients) {
		this.sPickIngredients = sPickIngredients;
	}
	/**
	 * @return the sPickIngredients
	 */
	public String getPickIngredients() {
		return sPickIngredients;
	}
	/**
	 * @param sSecretMethod the sSecretMethod to set
	 */
	public void setSecretMethod(String sSecretMethod) {
		this.sSecretMethod = sSecretMethod;
	}
	/**
	 * @return the sSecretMethod
	 */
	public String getSecretMethod() {
		return sSecretMethod;
	}
	/**
	 * @param sPreparation the sPreparation to set
	 */
	public void setPreparation(String sPreparation) {
		this.sPreparation = sPreparation;
	}
	/**
	 * @return the sPreparation
	 */
	public String getPreparation() {
		return sPreparation;
	}
	/**
	 * @param arIngredient the arIngredient to set
	 */
	public void setIngredient(ArrayList<Ingredient> arIngredient) {
		this.arIngredient = arIngredient;
	}
	/**
	 * @return the arIngredient
	 */
	public ArrayList<Ingredient> getIngredient() {
		return arIngredient;
	}
	/**
	 * @param arSteps the arSteps to set
	 */
	public void setSteps(ArrayList<Step> arSteps) {
		this.arSteps = arSteps;
	}
	/**
	 * @return the arSteps
	 */
	public ArrayList<Step> getSteps() {
		return arSteps;
	}
	public Integer getStepCount() {
		return arSteps.size();
	}
	public Boolean VGuideExist(Integer nStep) {
		String sVGuide = "";
		
		try {
			sVGuide = arSteps.get(nStep-1).getVGuide();
			if (sVGuide.equals("on")) return true;
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		}
		return false;
	}
	public String getStepVoiceAttachment(Integer nStep) {
		String sVAttachment = "";
		try {
			sVAttachment = arSteps.get(nStep-1).getVAttachment();
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());			
		}

		return sVAttachment;
	}
	public String getStepAttachment(Integer nStep) {
		String sAttachment = "";
		try {
			sAttachment = arSteps.get(nStep-1).getAttachment();	
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		}
		 
		return sAttachment;
	}
	public String getStepDescription(Integer nStep) {
		String sDescription = "";
		try {
			sDescription = arSteps.get(nStep-1).getDescription();	
		} catch (Exception e) {
			Log.d(TAG, e.getMessage());
		}
		 
		return sDescription;
	}
}

class JSONMainItems implements ServiceUrls {
	private static final String TAG = "JSONMainItems";
	
	private ArrayList<MainItem> alMainRecipe = new ArrayList<MainItem>();
	private ArrayList<MainItem> alMainSidedish = new ArrayList<MainItem>();
	private ArrayList<MainItem> alMainGroup = new ArrayList<MainItem>();
	private ArrayList<MainItem> alMainNotice = new ArrayList<MainItem>();
	
	private static String jString = "";
	
	public boolean bInitialized = false;
	
	private JSONArray jArr = null;
	
	@SuppressWarnings("unused")
	public void getItems(String sUrl) {
		int nCategoryNo = -1;	String sTitle = "";
		String sImgUrl = "";	String sLinkUrl = "";
		
		try {
			jString = CooknaviApp.getHttp(sUrl);
			jArr =  new JSONArray(jString);
			for (int index=0;index < jArr.length();index++) {
				JSONObject jObj = jArr.getJSONObject(index);
				nCategoryNo = jObj.getInt("cat"); 
				MainItem objItem = new MainItem();
				if (nCategoryNo==RECIPE_ITEM) { 
					// Recipe item
					objItem.setMainItem(nCategoryNo, jObj.getString("title"), jObj.getString("img"), jObj.getString("link"));
					alMainRecipe.add(objItem);
				} else if (nCategoryNo==SIDEDISH_ITEM) {
					// Sidedish item
					objItem.setMainItem(nCategoryNo, jObj.getString("title"), jObj.getString("img"), jObj.getString("link"));
					alMainSidedish.add(objItem);
				} else if (nCategoryNo==GROUP_ITEM) {
					// Group item
					objItem.setMainItem(nCategoryNo, jObj.getString("title"), jObj.getString("img"), jObj.getString("link"));
					alMainGroup.add(objItem);
				} else if (nCategoryNo==NOTICE_ITEM) {
					// Notice item
					objItem.setMainItem(nCategoryNo, jObj.getString("title"), jObj.getString("img"), jObj.getString("link"));
					alMainNotice.add(objItem);
				}
			}
			bInitialized = true;
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.d(TAG, "JSONMainItems :");
			e.printStackTrace();
		}
	}
	public ArrayList<MainItem> getRecipeArrayList() {
		return alMainRecipe;
	}
	public ArrayList<MainItem> getSidedishArrayList() {
		return alMainSidedish;
	}
	public ArrayList<MainItem> getGroupArrayList() {
		return alMainGroup;
	}
	public ArrayList<MainItem> getNoticeArrayList() {
		return alMainNotice;
	}
}

class MainItem {
	private static final String TAG = "MainItem";
	
	private int nCategory = 0;
	private String sTitle = "";
	private String sImgUrl = "";
	private String sLinkUrl = "";
	
	public MainItem() {
		
	}
	public void setMainItem(int nCategory, String sTitle, String sImgUrl, String sLinkUrl) {
		this.nCategory = nCategory;	this.sTitle = sTitle;
		this.sImgUrl = sImgUrl;		this.sLinkUrl = sLinkUrl;
	}
	@Override
	public String toString() {
		return sTitle;
	}
	public static String getTag() {
		return TAG;
	}
	public int getCategory() {
		return nCategory;
	}
	public String getTitle() {
		return sTitle;
	}
	public String getImgUrl() {
		return sImgUrl;
	}
	public String getLinkUrl() {
		return sLinkUrl;
	}
	public void clearMainItem() {
		nCategory = 0;	sTitle = "";
		sImgUrl = ""; 	sLinkUrl = "";
	}
}

class MainListViewWrapper {
	View base = null;
	ImageView item_thumb = null;
	TextView item_title = null;
	
	public MainListViewWrapper(View base) {
		// TODO Auto-generated constructor stub
		this.base = base;
	}
	ImageView getThumb() {
		if (item_thumb == null) {
			item_thumb = (ImageView)base.findViewById(R.id.item_thumb);
		}
		return item_thumb;
	}
	TextView getTitle() {
		if (item_title == null) {
			item_title = (TextView)base.findViewById(R.id.item_title);
		}
		return item_title;
	}
}

class MainRecipeAdapter extends ArrayAdapter<MainItem> {
	@SuppressWarnings("unused")
	private static String TAG = "MainRecipeAdapter";
	Context context;
	public ArrayList<MainItem> items;
	LayoutInflater li;
	
	private final ImageDownloader imageDownloader = new ImageDownloader();
	
	public MainRecipeAdapter(Context context, int textViewResourceId, ArrayList<MainItem> list) {
		super(context, textViewResourceId, list);
		this.context = context;
		this.items = list;
		li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	@Override
	public int getCount() {
		return items.size();
	}
	@Override
	public MainItem getItem(int position) {
		return items.get(position);
	}
	@Override
	public int getPosition(MainItem item) {
		return items.indexOf(item);
	}
	@Override
	public long getItemId(int position) {
		return position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		MainListViewWrapper viewWrapper;
		
		ImageView thumb = null;
		TextView title = null;
		
		if (v == null) {
			v = li.inflate(R.layout.listitem, null);
			viewWrapper = new MainListViewWrapper(v);
			v.setTag(viewWrapper);
		} else {
			viewWrapper = (MainListViewWrapper) v.getTag();
		}
		thumb = viewWrapper.getThumb();
		title = viewWrapper.getTitle();
		
		MainItem item = getItem(position);
		
		String tsThumb = ""; String tsTitle = "";
		tsThumb = item.getImgUrl(); tsTitle = item.getTitle();

		imageDownloader.download(tsThumb, thumb);
		title.setText(tsTitle);
		
		return v;
	}
}

class MainSidedishAdapter extends ArrayAdapter<MainItem> {
	@SuppressWarnings("unused")
	private static String TAG = "MainSidedishAdapter";
	Context context;
	public ArrayList<MainItem> items;
	LayoutInflater li;
	
	private final ImageDownloader imageDownloader = new ImageDownloader();
	
	public MainSidedishAdapter(Context context, int textViewResourceId, ArrayList<MainItem> list) {
		super(context, textViewResourceId, list);
		this.context = context;
		this.items = list;
		li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	@Override
	public int getCount() {
		return items.size();
	}
	@Override
	public MainItem getItem(int position) {
		return items.get(position);
	}
	@Override
	public int getPosition(MainItem item) {
		return items.indexOf(item);
	}
	@Override
	public long getItemId(int position) {
		return position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		MainListViewWrapper viewWrapper;
		
		ImageView thumb = null;
		TextView title = null;
		
		if (v == null) {
			v = li.inflate(R.layout.listitem, null);
//			v = li.inflate(R.layout.item, null);
			viewWrapper = new MainListViewWrapper(v);
			v.setTag(viewWrapper);
		} else {
			viewWrapper = (MainListViewWrapper) v.getTag();
		}
		thumb = viewWrapper.getThumb();
		title = viewWrapper.getTitle();
		
		MainItem item = getItem(position);
		
		String tsThumb = ""; String tsTitle = "";
		tsThumb = item.getImgUrl(); tsTitle = item.getTitle();

		imageDownloader.download(tsThumb, thumb);
		title.setText(tsTitle);
		
		return v;
	}
}

class MainGroupAdapter extends ArrayAdapter<MainItem> {
	@SuppressWarnings("unused")
	private static String TAG = "MainGroupAdapter";
	Context context;
	public ArrayList<MainItem> items;
	LayoutInflater li;
	
	private final ImageDownloader imageDownloader = new ImageDownloader();
	
	public MainGroupAdapter(Context context, int textViewResourceId, ArrayList<MainItem> list) {
		super(context, textViewResourceId, list);
		this.context = context;
		this.items = list;
		li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	@Override
	public int getCount() {
		return items.size();
	}
	@Override
	public MainItem getItem(int position) {
		return items.get(position);
	}
	@Override
	public int getPosition(MainItem item) {
		return items.indexOf(item);
	}
	@Override
	public long getItemId(int position) {
		return position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		MainListViewWrapper viewWrapper;
		
		ImageView thumb = null;
		TextView title = null;
		
		if (v == null) {
			v = li.inflate(R.layout.listitem, null);
//			v = li.inflate(R.layout.item, null);
			viewWrapper = new MainListViewWrapper(v);
			v.setTag(viewWrapper);
		} else {
			viewWrapper = (MainListViewWrapper) v.getTag();
		}
		thumb = viewWrapper.getThumb();
		title = viewWrapper.getTitle();
		
		MainItem item = getItem(position);
		
		String tsThumb = ""; String tsTitle = "";
		tsThumb = item.getImgUrl(); tsTitle = item.getTitle();

		imageDownloader.download(tsThumb, thumb);
		title.setText(tsTitle);
		
		return v;
	}
}

class MainNoticeAdapter extends ArrayAdapter<MainItem> {
	@SuppressWarnings("unused")
	private static String TAG = "MainNoticeAdapter";
	Context context;
	public ArrayList<MainItem> items;
	LayoutInflater li;
	
//	private final ImageDownloader imageDownloader = new ImageDownloader();
	
	public MainNoticeAdapter(Context context, int textViewResourceId, ArrayList<MainItem> list) {
		super(context, textViewResourceId, list);
		this.context = context;
		this.items = list;
		li = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	@Override
	public int getCount() {
		return items.size();
	}
	@Override
	public MainItem getItem(int position) {
		return items.get(position);
	}
	@Override
	public int getPosition(MainItem item) {
		return items.indexOf(item);
	}
	@Override
	public long getItemId(int position) {
		return position;
	}
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		MainListViewWrapper viewWrapper;
		
//		ImageView thumb = null;
		TextView title = null;
		
		if (v == null) {
			v = li.inflate(R.layout.simple_list_item, null);
			viewWrapper = new MainListViewWrapper(v);
			v.setTag(viewWrapper);
		} else {
			viewWrapper = (MainListViewWrapper) v.getTag();
		}
//		thumb = viewWrapper.getThumb();
		title = viewWrapper.getTitle();
		
		MainItem item = getItem(position);
		
//		String tsThumb = ""; 
		String tsTitle = "";
//		tsThumb = item.getImgUrl(); 
		tsTitle = item.getTitle();

//		imageDownloader.download(tsThumb, thumb);
		title.setText(tsTitle);
		
		return v;
	}
}
